<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 *  公众号商家联盟回调
 */
namespace app\allwin\controller\api\v4;
use app\allwin\controller\api\Base;
use app\allwin\model\AllwinUnmarket;
use app\allwin\model\AllwinUnmarketOrder;
use app\common\facade\Inform;
use app\common\facade\WechatPay;
use app\allwin\model\AllwinUnmarketReward;

class Unmarket extends Base{

    /**
     * 联合促销回调通知
     * @return void
     */
    public function Notify(){
        $response = WechatPay::doPay($this->miniapp_id)->handlePaidNotify(function($message, $fail) {
            $order = AllwinUnmarketOrder::where(['order_sn' => $message['out_trade_no'],'state' => 0])->find(); 
            if (empty($order)) {
                return true;
            }
            if ($message['return_code'] === 'SUCCESS') {
                if ($message['result_code'] === 'SUCCESS') {
                    $sub_mchid = $message['sub_mch_id'] ?? '';
                    $ispay = WechatPay::doPay($this->miniapp_id,true,$sub_mchid)->order->queryByOutTradeNumber($message['out_trade_no']);
                    if ($ispay['return_code'] === 'SUCCESS' && $ispay['trade_state'] === 'SUCCESS') {
                        $redpack_amount = AllwinUnmarketReward::redRacket($order);
                        $order->state   = 1;
                        $order->redpack = $redpack_amount;
                        $order->save();
                        $unmarket = AllwinUnmarket::where(['id' => $order->share_id])->find();
                        if($unmarket){
                            Inform::sms($order->uid,$this->miniapp_id,['title' =>'业务进展通知','type' => '活动参与','content' =>'您已成功参与'. $unmarket->title,'state' => '成功']);
                        }
                        return true;
                    } else {
                        return $fail('通信失败,请稍后再通知我');
                    }
                } else {
                    return $fail('通信失败,请稍后再通知我');
                }
            } else {
                return $fail('通信失败,请稍后再通知我');
            }
        });
        $response->send();
    }
}